package org.esjsoftware.v2m.rim.audio;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.RecordControl;

/**
 * 
 * @author Ernest
 * 
 */
public class AudioPlayer {
	private Manager manager;
	private Player recordPlayer;
	private Player player;
	private RecordControl recordControl;
	private ByteArrayOutputStream baos = null;

	public void record() throws IOException, MediaException {
//		if (recordPlayer == null) {
			recordPlayer = Manager.createPlayer("capture://audio");
			recordPlayer.realize();
//		}
		recordControl = (RecordControl) recordPlayer.getControl("RecordControl");
		recordControl.reset();
		if (recordControl != null) {
			baos = new ByteArrayOutputStream();
			recordControl.setRecordStream(baos);
			// recordControl.setRecordLocation(path);
			recordControl.startRecord();
			recordPlayer.start();
		}
	}

	public void recordPause() {
		if (recordControl != null) {
			System.out.println("PAUSE--SIZE = " + baos.size());
			recordControl.stopRecord();
		}
	}

	public void recordResume() {
		if (recordControl != null) {
			System.out.println("RESUME--SIZE = " + baos.size());
			recordControl.startRecord();
		}
	}

	public void recordCommit() throws IOException {
		if (recordControl != null) {
			recordControl.commit();
			System.out.println("COMMIT--SIZE = " + baos.size());
		}
	}
	
	public void recordStop() {
		if (recordControl != null) {
			recordControl.stopRecord();
		}
	}
	
	public ByteArrayOutputStream getAudio(){
		return baos;
	}
	
	public void playAudio(){
		InputStream is = new ByteArrayInputStream(baos.toByteArray());
		try {
			player = Manager.createPlayer(is, "audio/amr");
			player.start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MediaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
